const express=require('express');
const router=express.Router();
const query = require('../mysql')
const jwt = require('../utils/jwt')
router.post('/Login',function(req,res){
        var  sql = `SELECT * FROM my_user WHERE id='${req.body.name}' and pwd='${req.body.pwd}'`;
        query(sql,function (err,result) {
            if(err){ //sql 语句报错
                console.log(err.message);
                res.send({code:202,data:err,msg:"错误"})
                return;
            }
            if(result.length==0){
                res.send({code:201,data:result,msg:"ok"})
            }else{
                const tk = jwt.setToken({...result[0]})
                const data = {
                    userInfo:result[0],
                    token:tk,
                }
                res.send({code:200,data:data,msg:"ok"})
            }
        })
});

//获取用户分页
router.get('/getUser',function(req,res){
  const page = (req.query.pageNum-1)*req.query.pageSize
  var  sql = `SELECT *,(SELECT COUNT(*) FROM my_user) AS total FROM my_user limit ${page},${req.query.pageSize}`;
  query(sql,function (err,result,) {
      if(err){ //sql 语句报错
          res.send({code:202,data:err,msg:"错误"})
          return;
      }else{
        const data ={
          total:result[0].total,
          list:result
        }
        res.send({code:200,data:data,msg:"ok"})
      }
  })
});

//删除用户
router.post('/delUser',function(req,res){
  const sql = `DELETE FROM my_user WHERE id = '${req.body.id}'`;
  query(sql,function (err,result,) {
      if(err){ //sql 语句报错
          res.send({code:202,data:err,msg:"错误"})
          return;
      }else{
        res.send({code:200,data:true,msg:"ok"})
      }
  })
});

// 根据用户id 查询用户信息
router.post('/getUserInfoList',function(req,res){
 const sql = `SELECT * FROM my_user WHERE id IN (${req.body.userIds.map(id=>`'${id}'`).join(',')})`;
 query(sql,function (err,result,) {
        if(err){ //sql 语句报错
            res.send({code:202,data:err,msg:"错误"})
            return;
        }else{
            res.send({code:200,data:result,msg:"ok"})
        }
 })
})
module.exports = router
